package cn.com.b2office.service.impl;

import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.com.b2office.dao.DeliveryDao;
import cn.com.b2office.dao.ItemDao;
import cn.com.b2office.dao.MemberDao;
import cn.com.b2office.dao.OrderDao;
import cn.com.b2office.dao.PaymentModeDao;
import cn.com.b2office.dao.SpecialCategoryDao;
import cn.com.b2office.domain.Cart;
import cn.com.b2office.domain.CartItem;
import cn.com.b2office.domain.DeliveryTime;
import cn.com.b2office.domain.Item;
import cn.com.b2office.domain.MemberAddress;
import cn.com.b2office.domain.Order;
import cn.com.b2office.domain.OrderItem;
import cn.com.b2office.domain.SendDate;
import cn.com.b2office.service.CartService;

public class CartServiceImpl implements CartService {

	private ItemDao itemDao = null;

	private DeliveryDao deliveryDao = null;

	private SpecialCategoryDao specialCategoryDao = null;

	private OrderDao orderDao = null;

	private PaymentModeDao paymentModeDao = null;

	private MemberDao memberDao = null;

	public void addItemToCart(Cart cart, String itemId, int qty, int shape,
			String comments) {
		if (qty < 1)
			throw new IllegalArgumentException("qty=" + itemId);
		Item item = (Item) itemDao.getItem(itemId);
		if (item == null)
			throw new RuntimeException("can't find the item: itemId=" + itemId);
		if (item.getInventstate() == 1)
			throw new RuntimeException(item.getTitles() + "暂时缺货.");

		int newAdds = 1;

		CartItem cartItem = new CartItem();
		cartItem.setId(cart.getCartItemId_sequence());
		cartItem.setItemId(itemId);
		cartItem.setShape(shape);
		cartItem.setQty(qty);
		SendDate sendDate = createSendDate(item.getDeliverday(), cart
				.getShoppingTime());
		Map<SendDate, List<CartItem>> map = cart.getCartItems();

		boolean flag = false;// 是否已插入的标志
		Iterator<SendDate> iterator = map.keySet().iterator();
		while (iterator.hasNext()) {
			SendDate key = iterator.next();
			if (key.getDays() == sendDate.getDays()
					&& key.getTime().equals(sendDate.getTime())) {
				List<CartItem> list = map.get(key);
				if (list == null)
					list = new ArrayList<CartItem>();
				// 是否存在同样产品
				boolean exists = false;
				for (CartItem t : list) {
					if (t.getItemId().equals(cartItem.getItemId())
							&& t.getShape() == cartItem.getShape()) {
						t.setQty(t.getQty() + cartItem.getQty());
						exists = true;
						newAdds = 0;
						break;
					}
				}
				if (!exists)
					list.add(cartItem);
				flag = true;
				break;
			}
		}
		if (!flag) {
			List<CartItem> list = new ArrayList<CartItem>();
			list.add(cartItem);
			map.put(sendDate, list);
		}
		// 商品数量自增1
		cart.setCartSize(cart.getCartSize() + newAdds);
		// 订购金额自增
		double money = getCartItemMoney(cart, itemId, qty, shape);
		cart.setSum(cart.getSum() + money);
	}

	public void updateCartItemQty(Cart cart, int cartItemId, int qty) {
		if (qty <= 0)
			throw new RuntimeException("qty <=0 .");
		Map<SendDate, List<CartItem>> map = cart.getCartItems();
		Iterator<SendDate> iterator = map.keySet().iterator();
		while (iterator.hasNext()) {
			SendDate key = iterator.next();
			List<CartItem> list = map.get(key);
			for (CartItem t : list) {
				if (t.getId() == cartItemId) {
					t.setQty(qty);
					break;
				}
			}
		}
	}

	public Cart createAnonymousCart() {
		Cart cart = new Cart();
		cart.setShoppingTime(System.currentTimeMillis());
		// 默认不享受打折
		cart.setEnableDiscount(0);
		cart.setCartItems(new HashMap<SendDate, List<CartItem>>());
		// 默认支付方式
		cart.setPayMode(paymentModeDao.getDefaultPaymentMode().getIdno());
		// 默认配送方式
		cart.setDeliveryMode(deliveryDao.getDefaultDeliveryMode().getIdno());
		// 发票?
		return cart;
	}

	public double getCartItemMoney(Cart cart, String itemId, int qty, int shape) {
		Item item = itemDao.getItem(itemId);
		double price = item.getB2hprice();
		// 是否启用新订购单位
		if (item.getUsenewunit() == 1) {
			// 采用形状大小分类
			if (item.getUseshape() == 1) {
				if (shape == OrderItem.BIG_SHAPE) {
					price = item.getBigqty() * item.getB2hprice();
				} else if (shape == OrderItem.MID_SHAPE) {
					price = item.getMidqty() * item.getB2hprice();
				} else if (shape == OrderItem.SML_SHAPE) {
					price = item.getSmlqty() * item.getB2hprice();
				}
			} else {
				price = item.getMidqty() * item.getB2hprice();
			}
		}
		return qty * price;
	}

	/**
	 * change a anonymous cart to a member's shopping cart after the member
	 * login
	 * 
	 * @param cart
	 * @param memberId
	 */
	public void rebuildCart(Cart cart, String memberId) {
		cart.setMemberId(memberId);
		cart.setEnableDiscount(isEnableDiscount(memberId));
		MemberAddress regAddr = memberDao.getRegAddress(memberId);
		if (regAddr != null)
			cart.setAddressId(regAddr.getAddidno());
	}

	/** 构造购物车，并初始化状态 */
	public Cart createCart(String memberId) {
		Cart cart = new Cart();
		cart.setShoppingTime(System.currentTimeMillis());
		cart.setMemberId(memberId);
		cart.setEnableDiscount(isEnableDiscount(memberId));
		cart.setCartItems(new HashMap<SendDate, List<CartItem>>());
		// 默认配送地址
		MemberAddress regAddr = memberDao.getRegAddress(memberId);
		if (regAddr != null)
			cart.setAddressId(regAddr.getAddidno());
		// 默认支付方式
		cart.setPayMode(paymentModeDao.getDefaultPaymentMode().getIdno());
		// 默认配送方式
		cart.setDeliveryMode(deliveryDao.getDefaultDeliveryMode().getIdno());
		// 发票?
		return cart;
	}

	public CartItem getCartItem(Cart cart, int cartItemId) {
		Map<SendDate, List<CartItem>> map = cart.getCartItems();
		if (map == null)
			return null;
		Iterator iterator = map.keySet().iterator();
		while (iterator.hasNext()) {
			List<CartItem> cartItems = map.get(iterator.next());
			if (cartItems != null && cartItems.size() > 0) {
				for (int i = 0; i < cartItems.size(); i++) {
					CartItem c = cartItems.get(i);
					if (c.getId() == cartItemId) {
						return c;
					}
				}
			}
		}
		return null;
	}

	public void removeItemFromCart(Cart cart, int cartItemId) {
		Map<SendDate, List<CartItem>> map = cart.getCartItems();
		if (map == null)
			return;
		CartItem cartItem = null;
		Iterator<SendDate> iterator = map.keySet().iterator();
		boolean removeFlag = false;
		while (iterator.hasNext()) {
			SendDate key = iterator.next();
			List<CartItem> cartItems = map.get(key);
			if (cartItems != null && cartItems.size() > 0) {
				for (int i = 0; i < cartItems.size(); i++) {
					CartItem c = cartItems.get(i);
					if (c.getId() == cartItemId) {
						cartItem = cartItems.get(i);
						cartItems.remove(i);
						removeFlag = true;
						if (cartItems.isEmpty())
							map.remove(key);
						break;
					}
				}
			}
			// 如果移除了，则跳出迭代
			if (removeFlag)
				break;
		}
		if (cartItem != null) {
			// 商品数量自减1
			cart.setCartSize(cart.getCartSize() - 1);

			// 订购金额自减
			double money = getCartItemMoney(cart, cartItem.getItemId(),
					cartItem.getQty(), cartItem.getShape());
			cart.setSum(cart.getSum() - money);
			// 防止因为计算误差出现负号
			if (cart.getSum() <= 0)
				cart.setSum(0);
		}

	}

	public void clearCart(Cart cart) {
		Map<SendDate, List<CartItem>> map = cart.getCartItems();
		map = null;
		cart.setCartItems(new HashMap<SendDate, List<CartItem>>());
		cart.setCartSize(0);
		cart.setSum(0);

	}

	/**
	 * 判断用户是否享受打折待遇。当用户的第一次有效订单时间距离现在在7天之内，则享受此待遇。否则不享受。
	 * 
	 * @param memberid
	 * @return
	 */
	public int isEnableDiscount(String memberid) {
		boolean fg = false;
		Order order = null;
		order = orderDao.getFirstValidOrder(memberid);
		// 会员尚未有有效订单生成，此时享受打折活动
		if (order == null)
			return 1;
		Date potime = order.getOrderDate();
		Calendar calendar = Calendar.getInstance();
		Date current = calendar.getTime();
		calendar.setTime(potime);
		calendar.add(Calendar.DAY_OF_YEAR, 7);
		Date date2 = calendar.getTime();
		// 判断当前时间是否在（用户第一次下订单时间+7天）之前
		fg = current.before(date2);
		return fg ? 1 : 0;
	}

	/**
	 * 生成配送时间对象
	 * 
	 * @param deliveryHour
	 *            配送时间（小时）
	 * @return
	 */
	public SendDate createSendDate(int deliveryHour, long orderTime) {
		SendDate sendDate = new SendDate();
		// 正常配送商品
		DateFormat df = new SimpleDateFormat("HH:mm:ss");
		// TODO:此段代码需要优化
		Time currentTime = Time.valueOf(df.format(new Date(orderTime)));

		List<DeliveryTime> list = deliveryDao.findAllDeliveryTime();
		DeliveryTime deliveryTime = null;
		for (DeliveryTime dt : list) {
			if (dt.getBegintime().before(currentTime)
					&& dt.getEndtime().after(currentTime)) {
				deliveryTime = dt;
				break;
			}
		}
		// 如果仍为空,可能跨在时间点上
		if (deliveryTime == null) {
			for (DeliveryTime dt : list) {
				if (dt.getEndtime().compareTo(currentTime) == 0) {
					deliveryTime = dt;
					break;
				}
			}
		}
		if (deliveryTime == null)
			throw new RuntimeException("没有找到相关配送时间记录：current time="
					+ currentTime.toString());
		sendDate.setDays(deliveryTime.getSteps() + deliveryHour / 24);
		sendDate.setTime(deliveryTime.getDlvtime());
		return sendDate;
	}

	public void setDeliveryDao(DeliveryDao deliveryDao) {
		this.deliveryDao = deliveryDao;
	}

	public void setItemDao(ItemDao itemDao) {
		this.itemDao = itemDao;
	}

	public void setSpecialCategoryDao(SpecialCategoryDao specialCategoryDao) {
		this.specialCategoryDao = specialCategoryDao;
	}

	public void setOrderDao(OrderDao orderDao) {
		this.orderDao = orderDao;
	}

	public void setPaymentModeDao(PaymentModeDao paymentModeDao) {
		this.paymentModeDao = paymentModeDao;
	}

	public void setMemberDao(MemberDao memberDao) {
		this.memberDao = memberDao;
	}

}
